<template>
  <div class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem">
    <el-card shadow="never"
      class="box-card flex-sub"
      style="overflow: auto">
      <div class="div-query">
        <div class="collapse">
          <div class="collapse-header"
            @click="panelActive = !panelActive">
            <i class="collapse-header-icon"
              :class="[
                panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top'
              ]" />
            {{ panelActive ? "隐藏" : "展开" }}查询条件
          </div>
          <div class="collapse-content">
            <el-collapse-transition>
              <div v-show="panelActive">
                <el-form size="small"
                  label-position="right">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="设备编码"
                        label-width="120px">
                        <el-input v-model="searchModel.deviceSource"
                          placeholder="设备编码"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="设备名称"
                        label-width="120px">
                        <el-input v-model="searchModel.deviceName"
                          placeholder="设备名称"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="设备类型"
                        label-width="120px">
                        <el-select v-model="searchModel.deviceType"
                          placeholder="设备类型"
                          clearable
                          filterable>
                          <el-option v-for="item in deviceDictionaries"
                            :key="item.dictValue"
                            :label="item.dictText"
                            :value="item.dictValue" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="设备运行状态"
                        label-width="120px">
                        <el-select v-model="searchModel.deviceRunningState"
                          popper-class="global-select"
                          placeholder="选择设备运行状态"
                          clearable
                          filterable
                          @change="
                            e => {
                              if (e == '')
                                delete this.searchModel['deviceRunningState'];
                            }
                          ">
                          <el-option
                            v-for="item in searchArray.deviceRunningStateList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="使用情况"
                        label-width="120px">
                        <el-select v-model="searchModel.status"
                          popper-class="global-select"
                          placeholder="选择使用情况"
                          clearable
                          filterable>
                          <el-option v-for="item in searchArray.statusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="创建时间"
                        label-width="120px">
                        <el-date-picker v-model="searchModel.createdTime"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>

                    <!-- <el-col :span="8">
                      <el-form-item label="是否激活" label-width="120px">
                        <el-select
                          v-model="searchModel.isActive"
                          placeholder="选择是否激活"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="item in searchArray.isActiveList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col> -->
                  </el-row>
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="设备所在位置"
                        label-width="120px">
                        <el-input v-model="searchModel.deviceLocation"
                          placeholder="设备所在位置"
                          clearable
                          class="filter-item search-item" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8"
                      style="margin-left: 10px">
                      <el-form-item>
                        <el-button type="primary"
                          icon="el-icon-search"
                          @click="toSearch"
                          style="margin-right: 10px">搜索</el-button>
                        <el-button type="info"
                          icon="el-icon-delete"
                          @click="toReset"
                          style="margin-right: 10px">重置</el-button>
                        <el-button size="small"
                          @click="getDataList">
                          <i class="el-icon-refresh"
                            style="color: #606266" />
                          <span style="color: #606266">刷新</span>
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-transition>
          </div>
        </div>
      </div>

      <div>
        <div style="margin-bottom: 8px">
          <el-button size="small"
            type="primary"
            style="margin-right: 20px"
            @click="toAdd({ id: -1 }, 'add')">
            <i class="iconfont icon-xinzenghuizong"
              style="font-size: 13px;margin-right: 5px" />手动添加设备
          </el-button>
          <div v-if="selectedDataList.length != 0"
            class="alert-div">
            <i class="el-icon-info"
              style="color: #1890ff; margin-right: 3px" />
            已选择
            <strong style="color: #1890ff; margin: 0px 1px; font-size: 15px">
              {{ selectedDataList.length }}
            </strong>
            项
            <el-button type="text"
              style="padding: 10px"
              @click="toEmptySelection">清空</el-button>
          </div>
          <el-popover v-model="popoverVisible"
            placement="top"
            trigger="manual">
            <i class="el-icon-question"
              style="color: rgb(255, 153, 0)" />
            <span>
              确定要删除已选的
              <strong style="color: #1890ff; margin: 0px 1px">
                {{ selectedDataList.length }}
              </strong>
              项数据吗？
            </span>
            <div style="text-align: right; margin-top: 10px">
              <el-button size="mini"
                type="text"
                @click="popoverVisible = false">取消</el-button>
              <el-button type="primary"
                size="mini"
                @click="toBatchDeleteConfirm">确定</el-button>
            </div>
            <el-button slot="reference"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="toBatchDelete">
              批量删除
            </el-button>
          </el-popover>

          <el-button type="primary"
            icon="el-icon-download"
            size="small"
            @click="downloadTemplate"
            style="margin: 0px; float: right">下载模板</el-button>

          <el-upload :action="action"
            :on-change="handleChange"
            :headers="headers"
            style="float: right">
            <el-button type="info"
              icon="el-icon-upload"
              size="small"
              style="margin-right: 10px">
              批量导入设备
            </el-button>
          </el-upload>
        </div>

        <el-table ref="elTable"
          v-loading="loading || deleteLoading"
          border
          fit
          size="medium "
          :data="dataList"
          :row-key="row => row.id"
          style="width: 100%"
          :element-loading-text="deleteLoading ? '删除中,请等待...' : ''"
          @sort-change="onSortChange"
          @selection-change="onSelectionChange">
          <af-table-column align="center"
            type="selection"
            width="40"
            fixed
            :reserve-selection="true" />
          <el-table-column align="center"
            type="index"
            width="50"
            fixed
            label="#"
            :index="indexMethod" />

          <af-table-column align="center"
            label="设备编码"
            prop="deviceSource" />
          <af-table-column align="center"
            label="设备名称"
            prop="deviceName" />
          <af-table-column align="center"
            label="设备类型"
            prop="deviceTypeStr" />
          <af-table-column align="center"
            label="设备使用情况"
            prop="status"
            width="120px">
            <template slot-scope="{ row }">
              <el-tag size="medium"
                :style="row.status | constantKeyTagStyleObj('DEVICE_STATUS')">
                {{ row.status | constantKeyValue("DEVICE_STATUS") }}
              </el-tag>
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="设备运行状态"
            prop="deviceRunningState"
            width="120px">
            <template slot-scope="{ row }">
              <el-tag size="medium"
                :style="
                  row.deviceRunningState
                  | constantKeyTagStyleObj('DEVICE_RUNNING_STATE')
                ">
                {{
                  row.deviceRunningState
                  | constantKeyValue("DEVICE_RUNNING_STATE")
                }}
              </el-tag>
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="设备型号"
            prop="deviceModel" />

          <af-table-column align="center"
            label="设备所在位置"
            prop="deviceLocation">
            <template slot-scope="{ row }">
              <a class="a-text"
                @click="toLookLocation(row)">
                {{
                  row.gridMountFullPathText == null ||
                  row.gridMountFullPathText == ""
                  ? ""
                  : row.gridMountFullPathText + ">>"
                }}{{ row.deviceLocation }}
              </a>
            </template>
          </af-table-column>
          <af-table-column align="center"
            label="创建时间"
            prop="createdTime"
            sortable
            width="150" />

          <el-table-column align="center"
            label="操作区"
            fixed="right"
            width="150">
            <template slot-scope="{ row }">
              <el-tooltip effect="dark"
                content="详情"
                placement="top-start">
                <i class="iconfont icon-chakanxiangqing2 i-detail"
                  @click="toDetail(row)" />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark"
                content="编辑"
                placement="top-start">
                <i class="iconfont icon-bianji2 i-edit"
                  @click="toAdd(row, 'edit')" />
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark"
                content="删除"
                placement="top-start">
                <el-popconfirm :title="'确定删除【' + row.deviceName + '】该设备吗？'"
                  placement="top"
                  @confirm="toSingleDelete(row, $index, '确定')"
                  @cancel="toSingleDelete(row, $index, '取消')">
                  <i class="iconfont icon-shanchu i-delete"
                    slot="reference" />
                </el-popconfirm>
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark"
                content="关联摄像头"
                placement="top-start">
                <i class="
                            iconfont
                            icon-fenghuangxiangmutubiao_shexiangtou
                            i-edit
                          "
                  @click="toRelation(row)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0"
          :total="total"
          :page.sync="pagination.pageNum"
          :limit.sync="pagination.pageSize"
          :page-sizes="pageSizeOptions"
          @pagination="getDataList" />
      </div>
    </el-card>

    <device-add v-if="addDialogObj.isVisible"
      ref="addDialog"
      :dialog-visible="addDialogObj.isVisible"
      :title="addDialogObj.title"
      :params="params"
      @close="dialogClose('addDialogObj')"
      @submit="afterSubmit" />

    <device-detail v-if="detailDialogObj.isVisible"
      ref="detailDialog"
      :dialog-visible="detailDialogObj.isVisible"
      :title="detailDialogObj.title"
      :params="params"
      @close="dialogClose('detailDialogObj')" />

    <device-map v-if="deviceLocationDialogObj.isVisible"
      :dialog-visible="deviceLocationDialogObj.isVisible"
      :title="deviceLocationDialogObj.title"
      :device-location="clickedDeviceLocation"
      :max-height-dialog="maxHeightDialog"
      :list-type="'查看详情'"
      :device-obj="clickedDeviceObj"
      @close="dialogClose('deviceLocationDialogObj')" />
    <relation v-if="isRelationVisible"
      ref="relationDialog"
      :dialog-visible="isRelationVisible"
      :params="params"
      @close="dialogRelationClose()" />
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import dataTableMixins from "@/mixins/data-table-mixins";
import deviceManageApi from "@/api/device-manage";
import recDataDeviceList from "./device-list.js";
import DeviceAdd from "./component/Add";
import DeviceDetail from "./component/Detail";
import DeviceMap from "./component/Map";
import Relation from "./component/relation.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "DeviceList",
  components: {
    Pagination,
    DeviceAdd,
    DeviceDetail,
    DeviceMap,
    Relation
  },
  mixins: [dataTableMixins],
  data () {
    return {
      searchArray: recDataDeviceList.RecDataSearchArray,
      deleteLoading: false,
      popoverVisible: false,
      maxHeightDialog: "0px",
      deviceLocationDialogObj: {
        isVisible: false,
        title: ""
      },
      clickedDeviceLocation: "",
      clickedDeviceObj: {},
      isRelationVisible: false,
      params: null,

      deviceDictionaries: [],
      action: process.env.VUE_APP_BASE_API + "main/equipment/uploadExcel",
      headers: {
        Authorization: `bearer ${getToken()}`
      }
    };
  },
  created () { },
  mounted () {
    this.getDictValueAttr();
  },
  methods: {
    getDictValueAttr () {
      const data = {
        fieldName: "collect_type",
        tableName: "t_equipment_collect"
      };
      deviceManageApi.getDictValueAttr(data).then(ret => {
        this.deviceDictionaries = ret.data.dictValue;
        this.getDataList();
      });
    },
    getDataList () {
      this.loading = true;
      this.searchModel.deviceIsLine = 1;
      const searchModel = this.formatSearchData(this.searchModel);

      if (Array.isArray(this.searchModel.createdTime)) {
        searchModel.createdTimeFrom = this.searchModel.createdTime[0];
        searchModel.createdTimeTo = this.searchModel.createdTime[1];
      }
      searchModel.createdTime = null;

      deviceManageApi
        .getDeviceList({ ...this.pagination, ...searchModel, ...this.sort })
        .then(ret => {
          this.dataList = ret.data.data.rows;

          this.dataList.forEach((ele, i) => {
            this.selectedDataList.forEach((multEle, j) => {
              if (this.dataList[i].id === this.selectedDataList[j].id) {
                this.$refs.elTable.toggleRowSelection(this.dataList[i], true);
              }
            });

            this.deviceDictionaries.forEach((ele1, i1) => {
              if (Number(ele.deviceType) === ele1.dictValue) {
                ele.deviceTypeStr = ele1.dictText;
              }
            });

            // if (ele.isActive == 1) {
            //   ele.isActive = '激活'
            // } else {
            //   ele.isActive = '未激活'
            // }
          });
          this.total = ret.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.dataList = [];
          this.total = 0;
        });
    },
    toSearch () {
      this.pagination.pageNum = 1;
      this.getDataList();
    },
    toReset () {
      this.searchModel = {};
      this.sort = {};
      this.$refs.elTable.clearSort();
      this.$refs.elTable.clearFilter();
      this.toSearch();
    },
    onSortChange (val) {
      console.log(val);
      this.sort.field = val.prop;
      this.sort.order = val.order;
      this.toSearch();
    },
    onSelectionChange (selection) {
      this.selectedDataList = selection;
    },
    toEmptySelection () {
      this.$refs.elTable.clearSelection();
    },
    indexMethod (index) {
      return this.formatIndex(index, this.pagination);
    },
    toBatchDelete () {
      if (this.selectedDataList.length === 0) {
        this.$message({
          message: "请先选择需要删除的数据",
          type: "warning",
          duration: 4000
        });
        return;
      } else {
        this.popoverVisible = true;
      }
    },
    toBatchDeleteConfirm () {
      this.popoverVisible = false;
      const ids = [];
      this.selectedDataList.forEach(ele => {
        ids.push(ele.id);
      });
      this.deleteConfirm(ids);
    },
    toSingleDelete (data, index, type) {
      if (type === "确定") {
        this.deleteConfirm(data.id, "");
      }
    },
    deleteConfirm (ids) {
      console.log("删除ids", ids);
      this.deleteLoading = true;
      deviceManageApi
        .deleteDevice(ids)
        .then(() => {
          this.$message.success("删除成功！");
          this.deleteLoading = false;
          this.toEmptySelection();
          this.toReset();
        })
        .catch(() => {
          this.deleteLoading = false;
        });
    },
    toDetail (data) {
      this.params = {
        item: data
      };
      this.detailDialogObj.title = "无线设备 ＞详情";
      this.detailDialogObj.isVisible = true;
    },
    toAdd (data) {
      this.params = {
        item: data
      };
      this.addDialogObj.title =
        data.id === -1 ? "无线设备 ＞添加" : "无线设备 ＞编辑";
      this.addDialogObj.isVisible = true;
    },
    afterSubmit (operationType) {
      if (operationType === "add") {
        this.toReset();
      } else {
        this.getDataList();
      }
    },
    toLookLocation (data) {
      if (data.deviceLocation && data.deviceLocation !== "") {
        this.maxHeightDialog = this.getHeightAndWidth();
        this.deviceLocationDialogObj.title = "设备位置";
        this.deviceLocationDialogObj.isVisible = true;
        this.clickedDeviceLocation = data.deviceLocation;
        this.clickedDeviceObj = data;
      }
    },
    getHeightAndWidth () {
      let clientHeight = 0;
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5; // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5; // 网页可见区域高
      }
      return clientHeight - 220 + "px";
    },
    toRelation (row) {
      this.params = row;
      this.isRelationVisible = true;
    },
    dialogRelationClose () {
      this.params = null;
      this.isRelationVisible = false;
    },
    handleChange (file, fileList) {
      console.log("file", file);
      const loading = this.$loading({
        lock: true,
        text: "正在导入数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      switch (file.status) {
        case "ready":
          break;
        case "success":
          loading.close();
          // if (file.response == '导入成功') {
          //   this.$message.success(`${file.name} 文件导入成功.`)
          // } else {
          //   this.$message.error('导入文件失败，失败原因：' + file.response.msg)
          // }
          // this.toReset()

          let str = "";
          if (file.response && file.response.length !== 0) {
            file.response.forEach(ele => {
              str = str + `<div>${ele}</div>`;
            });
          }
          this.$alert(str, "提示", {
            dangerouslyUseHTMLString: true,
            callback: action => {
              this.toReset();
            }
          });

          break;
        case "fail":
          loading.close();
          this.$message.error("导入文件失败，请重新导入！");
      }
    },
    // 下载模板
    downloadTemplate () {
      window.location.href =
        "http://47.106.193.127:8231/uploads/sys-file/device/设备导入模板-参照.xls";
    },
    selectChange (e) {
      console.log(e == "");
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../../../styles/part-custom";
</style>
